<template>
  <div class="noveldetail">
    <div class="nav">
      <van-nav-bar
        left-text="返回"
        title="书籍详情"
        left-arrow
        @click-left="back"
      >
      </van-nav-bar>
    </div>
    <div class="top">
      <div class="top-img">
        <img :src="img" alt="" @error="handleError($event)" />
      </div>
      <div class="top-text">
        <div class="title">{{ BookDetails.title }}</div>
        <div class="author">
          {{ prisbook.category }} | <span style="color: red">{{ author }}</span>
        </div>
        <div class="xing">
          <van-rate
            v-model="value"
            :size="18"
            color="#ffd21e"
            void-icon="star"
            void-color="#999"
            readonly
          />
        </div>
        <div class="words">
          {{ words }}万字 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ clicksCount }}点击
        </div>
      </div>
    </div>
    <div class="content">
      <div class="content-text">
        <div class="text">{{ BookDetails.summary }}</div>
        <div class="icon">
          <van-icon class="icon-arrow" name="arrow-down" @click="getmore" />
        </div>
        <div class="paydesc">作品类型：{{ prisbook.paydesc }}</div>
      </div>
    </div>
    <!-- 目录 -->
    <div class="cnt" @click="getid(pid)">
      <van-nav-bar>
        <template #left>
          <van-icon name="bars" size="18" />
          <span> 共&nbsp;{{ totalArticleCount }}&nbsp;章</span>
        </template>
        <template #right>
          <span></span>
          <van-icon name="arrow" size="18" />
        </template>
      </van-nav-bar>
    </div>
    <!-- 评论 -->
    <div class="comment">
      <div class="comment-left">
        <van-icon name="comment-o" />
        <span>评论</span>
      </div>
      <div class="comment-right">
        <van-tag color="#7232dd" plain size="medium">
          <van-icon name="edit" size="medium" />
          写评论
        </van-tag>
      </div>
    </div>
    <div class="comment-list">
      <div class="item" v-for="(item, i) in commentList" :key="i">
        <div class="item-left">
          <div class="round">
            <img
              :src="item.avatar ? item.avatar : userimg"
              alt=""
              @error="userPError($event)"
            />
            <div class="dashi">一钱大师</div>
          </div>
        </div>
        <div class="item-right">
          <div class="username">
            <div class="name">
              {{ item.nickName }}
              <span class="tag">&nbsp;LV.{{ level[i] }}&nbsp;</span>
            </div>
          </div>
          <div class="time">{{ getTime(item.time) }}</div>
          <div class="text">
            {{ item.comment }}
          </div>
        </div>
      </div>
    </div>
    <div class="foot">
      <div class="foot-left" @click="addBookshelf()">
        {{ addBook ? "加入书架" : "已加入书架" }}
      </div>
      <div class="foot-cnt" @click="getBookcontentId">免费试读</div>
      <div class="foot-right">购买</div>
    </div>
  </div>
</template>

<script>
export default {
  name: "noveldetail",
  data() {
    return {
      activeName: "",
      pid: "",
      img: "",
      words: "",
      author: "",
      clicksCount: "",
      BookDetails: [],
      prisbook: [],
      totalArticleCount: "",
      flag: 1,
      value: 0,
      time: "1644226886640",
      bookId: "",
      commentList: [],
      level: [],
      userId: [],
      userimg:
        "https://thirdwx.qlogo.cn/mmopen/vi_32/Q3auHgzwzM4rU5CtibQTAMK7ibj8k6je3K2W4GoVFJbMu6wYCdXsIVE4tkXH2AfibPZU3D8XQFb46ahm6qTXyltvw/132",
      secId: "",
      addBook: true,
      //登录状态
      isLogin: true,
    };
  },
  created() {
    this.pid = this.$route.params.pid;
    //获取小说详情
    this.getNoveldetail(this.pid);
    //获取书籍目录
    this.getCatalogue(this.pid);
    //获取登录状态
    this.getLogin();
  },
  methods: {
    //日期
    getTime(time) {
      let r = new Date(time);
      let month = r.getMonth() + 1;
      let date = r.getDate();
      let year = r.getFullYear();
      return year + "年" + month + "月" + date + "日";
    },

    //传递书籍的id
    getid(pid) {
      let title = this.BookDetails.title;
      // console.log("title==>", title);
      // console.log("pid ==> ", pid);
      this.$router.push({ name: "catalogue", params: { pid } });
    },
    //没有书籍图片的话用默认书籍图片
    handleError(e) {
      e.currentTarget.src =
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fc823bc165add16c76bdefaee090c45c202267a452deaa-lLhkHf_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1650685371&t=e67779564f0416a69ca07519acf1045b";
    },
    //没有用户头像图片的话用默认用户图片
    userPError(e) {
      e.currentTarget.src =
        "https://thirdwx.qlogo.cn/mmopen/vi_32/Q3auHgzwzM4rU5CtibQTAMK7ibj8k6je3K2W4GoVFJbMu6wYCdXsIVE4tkXH2AfibPZU3D8XQFb46ahm6qTXyltvw/132";
    },

    //返回上一级
    back() {
      this.$router.go(-1);
    },
    //获取更多简介
    getmore() {
      let iconarrow = document.querySelector(".icon-arrow");
      let text = document.querySelector(".text");
      let paydesc = document.querySelector(".paydesc");
      if (this.flag == 1) {
        iconarrow.classList.remove("van-icon-arrow-down");
        iconarrow.classList.add("van-icon-arrow-up");
        text.style.display = "block";
        paydesc.style.display = "block";
        this.flag = 0;
      } else if (this.flag == 0) {
        iconarrow.classList.remove("van-icon-arrow-up");
        iconarrow.classList.add("van-icon-arrow-down");
        text.style.display = "-webkit-box";
        paydesc.style.display = "none";
        this.flag = 1;
      }
    },
    //根据id获取书籍详情
    getNoveldetail(id) {
      //发起申请
      this.axios({
        //请求类型
        method: "get",
        //请求路径
        url: "https://apis.netstart.cn/yunyuedu/book/getsub.json",
        params: {
          id,
        },
      })
        .then((result) => {
          this.img = result.data.feed.entry.link[2].href;
          // let word = result.data.feed.entry["pris:book"].words;
          this.words = (
            result.data.feed.entry["pris:book"].words / 10000
          ).toFixed(1);
          this.BookDetails = result.data.feed.entry;
          this.prisbook = result.data.feed.entry["pris:book"];
          //作者
          this.author = result.data.feed.entry.author.name;
          //点击次数
          this.clicksCount = this.BookDetails["pris:subscribe"].clicksCount;
          //总章节
          this.totalArticleCount = this.prisbook.totalArticleCount[0];
          //评分
          this.value = parseInt(this.BookDetails["pris:ranking"].value);
          //获取书籍id
          this.bookId = this.BookDetails.id;
          //获取书籍评论
          this.getComment(this.bookId);

          this.lookBook();
        })
        .catch((err) => {
          console.log("err ==> ", err);
        });
    },
    //书籍评论
    //获取书籍评论
    getComment(bookId) {
      //发起申请
      this.axios({
        //请求类型
        method: "get",
        //请求路径
        url: "https://apis.netstart.cn/yunyuedu/comment/getComments.json",
        params: {
          bookId,
        },
      })
        .then((result) => {
          this.commentList = result.data.all.list;
          this.commentList.forEach((v) => {
            const userId = v.userId;
            this.userId.push(v.userId);
            this.getUserlevel(userId);
          });
        })
        .catch((err) => {
          console.log("err ==> ", err);
        });
    },
    //获取用户等级
    getUserlevel(userId) {
      //发起申请
      this.axios({
        //请求类型
        method: "get",
        //请求路径
        url: "https://apis.netstart.cn/yunyuedu/sns/user/getUserInfo.json",
        params: {
          userId,
        },
      })
        .then((result) => {
          this.level.push(result.data.userInfo.levelInfo.info.common.level);
        })
        .catch((err) => {
          console.log("err ==> ", err);
        });
    },
    //根据id获取书籍目录
    getCatalogue(source_uuid) {
      //发起申请
      this.axios({
        //请求类型
        method: "get",
        //请求路径
        url: "https://apis.netstart.cn/yunyuedu/reader/book/info.json",
        params: {
          source_uuid,
        },
      })
        .then((result) => {
          // console.log("result.data.data.catalog==>", result.data.data.catalog);
          let data = result.data.data.catalog;
          // console.log("data[1].secId==>", data[1].secId);
          this.secId = data[0].secId;
        })
        .catch((err) => {
          console.log("err ==> ", err);
        });
    },
    //得到章节内容的id
    getBookcontentId() {
      let secId = this.secId;
      let bookId = this.bookId;
      this.$router.push({ name: "bookcontent", params: { secId, bookId } });
    },
    //点击加入书架
    addBookshelf() {
      let books = localStorage.getItem("books");
      if (!books) {
        books = [];
      } else {
        books = JSON.parse(books);
      }
      //判断是否存在重复的搜索关键字
      for (var i = 0; i < books.length; i++) {
        if (books[i].bookId === this.bookId) {
          //如果找到, 则终止执行
          return;
        }
      }
      if (this.isLogin === false) {
        this.$toast("没有登录不能添加进书架，请前往登录！");
        setTimeout(() => {
          this.$router.push({ name: "login" });
        }, 1000);
        return;
        // setTimeout(() => {
        //   console.log(111111);
        // }, 1000);
      }
      //如果id为空则不添加
      if (this.bookId === "") {
        return;
      }
      books.push({ bookId: this.bookId });
      this.addBook = false;
      localStorage.setItem("books", JSON.stringify(books));
    },
    //从本地储存查找是否已经添加过
    lookBook() {
      let books = JSON.parse(localStorage.getItem("books"));
      if (books) {
        books.forEach((v) => {
          if (this.bookId === v.bookId) {
            this.addBook = false;
          }
        });
      }
    },
    //获取登录状态
    getLogin() {
      let loginUserInfo = JSON.parse(localStorage.getItem("loginUserInfo"));
      if (!loginUserInfo) {
        this.isLogin = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.noveldetail {
  width: 100%;
  height: 100%;
  .top {
    background-color: #eee;
    margin-top: 2px;
    padding: 20px;
    display: flex;

    .top-img {
      width: 100px;
      margin-left: 10px;
      border-radius: 10px;
      img {
        width: 100px;
        border-radius: 10px;
      }
    }
    .top-text {
      margin-left: 10px;
      .title {
        font-size: 15px;
        font-weight: bold;
        margin-bottom: 10px;
      }
      .author {
        margin-bottom: 10px;
      }
      .xing {
        margin-bottom: 10px;
      }
    }
  }
  .content {
    padding-left: 25px;
    padding-right: 25px;
    background-color: #eee;
    .content-text {
      position: relative;
      padding-bottom: 10px;

      .text {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
        margin-bottom: 10px;
      }
      .paydesc {
        display: none;
      }
      .icon {
        position: absolute;
        right: 0;
        bottom: 10px;
      }
    }
  }

  .cnt {
    border-top: 1px solid #666;
    border-bottom: 1px solid #666;
    background-color: #eee;

    span {
      margin-left: 20px;
    }
  }
  .comment {
    margin-top: 10px;
    // background-color: #eee;
    padding: 10px 16px;
    position: relative;
    font-size: 20px;
    span {
      margin-left: 10px;
    }
    .comment-right {
      position: absolute;
      top: 7px;
      right: 25px;
    }
  }
  .comment-list {
    padding: 10px 20px 50px 20px;
    .item {
      display: flex;
      margin-bottom: 15px;
      padding: 10px 0px;
      .item-left {
        width: 50px;
        position: relative;
        margin-right: 20px;
        .round {
          width: 50px;
          height: 50px;
          margin: 0 auto;
          border-radius: 50%;
          background-color: #eee;
          img {
            width: 50px;
            border-radius: 50%;
          }
        }
        .dashi {
          width: 65px;
          text-align: center;
          background-color: rgb(73, 200, 231);
          border-radius: 20px;
          position: absolute;
          top: 38px;
          left: -7px;
        }
      }
      .item-right {
        .username {
          // position: relative;
          display: flex;
          .name {
            font-size: 15px;
            color: rgb(115, 204, 240);
            .tag {
              font-size: 13px;
              color: red;
              border: 1px solid red;
              margin-left: 10px;
            }
          }
        }
        .time {
          margin: 5px auto;
        }
      }
    }
  }
  .foot {
    width: 100%;
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    display: flex;
    font-size: 20px;
    text-align: center;
    .foot-left {
      width: 33%;
      background-color: #eee;
    }
    .foot-cnt {
      width: 33%;
      color: #fff;
      background-color: red;
    }
    .foot-right {
      width: 34%;
      background-color: #eee;
    }
  }
}
</style>